package com.stars.easyms.logging.log4j2;

import com.stars.easyms.logging.constant.EasyMsLoggingConstants;
import com.stars.easyms.logging.log4j2.xml.EasyMsLog4j2XmlConfiguration;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.springframework.boot.logging.LogFile;
import org.springframework.boot.logging.log4j2.Log4J2LoggingSystem;
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;

/**
 * <p>className: EasyMsLog4J2LoggingSystem</p>
 * <p>description: EasyMs自定义Log4J2LoggingSystem类</p>
 *
 * @author guoguifang
 * @version 1.7.0
 * @date 2020/11/16 2:37 下午
 */
public class EasyMsLog4J2LoggingSystem extends Log4J2LoggingSystem {

    public EasyMsLog4J2LoggingSystem(ClassLoader classLoader) {
        super(classLoader);
    }

    @Override
    protected void loadConfiguration(String location, LogFile logFile) {
        Assert.notNull(location, "Location must not be null");
        LoggerContext ctx = getEasyMsLoggerContext();
        URL url;
        try {
            url = ResourceUtils.getURL(location);
        } catch (FileNotFoundException e) {
            return;
        }
        try (InputStream stream = url.openStream()) {
            ConfigurationSource source;
            if (EasyMsLoggingConstants.FILE_PROTOCOL.equals(url.getProtocol())) {
                source = new ConfigurationSource(stream, ResourceUtils.getFile(url));
            } else {
                source = new ConfigurationSource(stream, url);
            }

            ctx.start(new EasyMsLog4j2XmlConfiguration(ctx, source));
        } catch (Exception ex) {
            throw new IllegalStateException("Could not initialize Log4J2 logging from " + location, ex);
        }
    }

    private LoggerContext getEasyMsLoggerContext() {
        return (LoggerContext) LogManager.getContext(false);
    }

}
